#include "Logger.hpp"
#include "InetAddr.hpp"
#include "Protocol.hpp"
#include "Socket.hpp"

#include <iostream>

void Usage(std::string proc)
{
    std::cerr << "Usage: " << proc << " serverport serverip" << std::endl;
}

//./server serverip serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return 0;
    }
    std::cout << "进入 main 函数" << std::endl;
    uint16_t serverport = std::stoi(argv[2]);
    std::string serverip = argv[1];
    InetAddr server(serverport, serverip);
    // 创建套接字
    std::unique_ptr<Socket> sockptr = std::make_unique<TcpSocket>();
    sockptr->BuildSockfd();
    std::cout << "创建套接字成功" << std::endl;

    // 向服务器发起连接请求
    if (sockptr->Connect(server))
    {
        std::cout << "向服务器发起连接成功" << std::endl;
        // 成功了就向其中写入数据、读数据
        std::string inbuffer; // 接受缓冲区
        while (true)
        {
            // std::string line;
            // std::cout << "Please enter# ";
            // std::getline(std::cin , line);
            // 1、构建请求
            Request req;
            std::cout << "Please enter X: ";
            std::cin >> req._x;
            std::cout << "Please enter Y: ";
            std::cin >> req._y;
            std::cout << "Please enter Oper: ";
            std::cin >> req._oper;

            // 2、序列化
            std::string jsonstr;
            if (req.Seriailze(&jsonstr) == false)
                continue;

            // 3、打包
            std::string reqstr = Protocol::Package(jsonstr);

            // std::cout << "reqstr：" << reqstr << std::endl;

            // 4、发送给服务器
            //  int n = send(sockptr->Sockfd() , line.c_str(), line.size() , 0);
            sockptr->Send(reqstr);
            // std::cout << "发送完毕" << std::endl;
            // 5、获取应答
            sockptr->Recv(&inbuffer);
            // std::cout << "获取完报文" <<  inbuffer << std::endl;
            // 6、解包
            std::string package;
            int n = Protocol::Unpack(inbuffer, &package);
            // std::cout << "解包成功 n: " << n;
           if(n>0)
            {
                // 7、反序列化
                Response resp;
                bool r = resp.Deserialze(package);
                if (r)
                {
                    // 8、将处理结果打印出来
                    resp.Print();
                }
            }
        }
    }

    return 0;
}